package com.fanghuaman.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fanghuaman.common.util.SecurityUtil;
import com.fanghuaman.model.common.vo.ResponseResult;
import com.fanghuaman.model.user.dto.LoginDto;
import com.fanghuaman.model.user.dto.RegisterDto;
import com.fanghuaman.model.user.dto.UserEditDto;
import com.fanghuaman.model.user.pojo.User;
import com.fanghuaman.user.mapper.UserMapper;
import com.fanghuaman.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author smh
 * @since 2024-11-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, loginDto.getUsername())
                .eq(User::getPassword, loginDto.getPassword());
        User user = userMapper.selectOne(wrapper);
        if (user != null){
            // 生成token

            return ResponseResult.success();
        }else {
            return ResponseResult.fail("登录失败");
        }
    }

    /**
     * 注册
     *
     * @param registerDto
     * @return
     */
    @Override
    public ResponseResult register(RegisterDto registerDto) {
        boolean check = registerDto.check();
        if (!check) {
            return ResponseResult.fail("参数校验失败");
        }
        // 查询数据库,是否用户名重复
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, registerDto.getUsername()));
        if (user != null) {
            return ResponseResult.fail("用户名重复");
        }
        //对于密码进行加密
        String password = registerDto.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        registerDto.setPassword(encode);

        // 插入数据库
        user = BeanUtil.copyProperties(registerDto, User.class);
        user.setSex(2); // 默认性别为未知
        user.setNickname(user.getUsername()); // 默认昵称为用户名
        user.setUpdateTime(new Date()); // 更新时间
        user.setCreateTime(new Date()); // 创建时间
        int insert = userMapper.insert(user);
        if (insert <= 0) {
            return ResponseResult.fail("注册失败");
        }
        return ResponseResult.success();
    }

    /**
     * 忘记密码
     *
     * @param registerDto
     * @return
     */
    @Override
    public ResponseResult forgetPassword(RegisterDto registerDto) {
        if (!registerDto.check()) {
            return ResponseResult.fail("参数校验失败");
        }
        // 查询用户
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, registerDto.getUsername()));
        if (user == null) {
            return ResponseResult.fail("用户不存在");
        }
        if (!user.getPhone().equals(registerDto.getPhone())) {
            return ResponseResult.fail("手机号不匹配");
        }

        //修改密码
        // 先对密码进行加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(registerDto.getPassword());
        user.setPassword(encode);
        int update = userMapper.update(user, Wrappers.lambdaUpdate(User.class).eq(User::getId, user.getId()));
        if (update <= 0) {
            return ResponseResult.fail("修改失败");
        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult edit(UserEditDto userEditDto) {
        // 校验是否登录
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SecurityUtil.User user = SecurityUtil.getUser(principal.toString());
        if (user == null) {
            return ResponseResult.fail("未登录");
        }

        // 修改信息
        User updateUser = new User();
        BeanUtils.copyProperties(userEditDto, updateUser);
        updateUser.setUpdateTime(new Date());
        int i = userMapper.updateById(updateUser);
        if (i <= 0) {
            return ResponseResult.fail("修改失败");
        }
        return ResponseResult.success("修改成功");
    }
}
